package com.minis.beans.factory;

import com.minis.beans.exception.BeansException;
import com.minis.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor;
import com.minis.beans.factory.config.BeanDefinition;
import com.minis.beans.factory.config.BeanPostProcessor;
import com.minis.beans.factory.support.AbstractAutowireCapableBeanFactory;
import com.minis.beans.factory.support.ConfigurableListableBeanFactory;

import java.util.*;

/**
 * IOC 引擎
 */
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
        implements ConfigurableListableBeanFactory {
    @Override
    public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
        super.addBeanPostProcessor((AutowiredAnnotationBeanPostProcessor) beanPostProcessor);
    }

    @Override
    public void registerDependentBean(String beanName, String dependentBeanName) {
        BeanDefinition bd = getBeanDefinition(beanName);
        bd.setDependsOn(dependentBeanName);
    }

    @Override
    public String[] getDependentBeans(String beanName) {
        BeanDefinition bd = getBeanDefinition(beanName);
        return bd.getDependsOn();
    }


    @Override
    public int getBeanDefinitionCount() {
        return this.getBeanDefinitionMap().size();
    }

    @Override
    public String[] getBeanDefinitionNames() {
        return this.getBeanDefinitionName().toArray(new String[0]);
    }

    @Override
    public String[] getBeanNamesForType(Class<?> type) {
        List<String> res = new ArrayList<>();
        for (String beanName : this.getBeanDefinitionNames()) {
            BeanDefinition beanDefinition = this.getBeanDefinition(beanName);
            Class<?> clazz = beanDefinition.getClass();
            if (type.isAssignableFrom(clazz)) {
                res.add(beanName);
            }
        }
        return res.toArray(new String[0]);
    }

    @Override
    public <T> Map<String, T> getBeansOfType(Class<T> type) throws BeansException {
        String[] beanNames = this.getBeanNamesForType(type);
        Map<String, T> res = new LinkedHashMap<>(beanNames.length);
        for (String beanName : beanNames) {
            Object bean = getBean(beanName);
            res.put(beanName,(T) bean);
        }
        return res;
    }

    // Dispatcher 改造
    ConfigurableListableBeanFactory parentBeanFactory;
    public void setParent(ConfigurableListableBeanFactory beanFactory) {
        this.parentBeanFactory = beanFactory;
    }

    // case1：对于 Ioc 容器，直接调用父类的 getBean()
    // case2：对于 MVC 容器，先从调用父类的 getBean() ，若为空则再从 Ioc 容器获取
    @Override
    public Object getBean(String beanName) throws BeansException {
        Object result =  super.getBean(beanName);
        if (result == null) {
            result = this.parentBeanFactory.getBean(beanName);
        }
        return result;
    }
}
